<template>
 <div class="borrower">

      <el-card class="box-card" shadow="never" style="border:0px;">
        <el-button style="float:right;" type="primary" size="mini" v-if="defaultChangeValue!='detail'" @click="batchSaveOwnerBorrowerDraft(2)" >保存草稿</el-button>
        <el-form :model="formData3"  ref="formData3" status-icon label-position="right" label-width="100px" style="width: 80%; margin-left:50px;" >
        <el-collapse v-model="activeNames" accordion class="parentColl">
        <el-collapse-item 
        v-for="(item,index) in formData3.powerAttrList"
        :key="item.key"  
        style="border-bottom: 1px solid #f0f0f0;padding: 10px;" :title="item.title" :name="item.num">
                
                <el-form-item
                  label="姓名"
                  :prop="'powerAttrList.' + index + '.realName'"
                  :rules="[{ required: true, message: '请输入姓名',trigger: 'blur'}]"
                >
                  <el-input v-model="item.realName" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item
                  label="身份证号"
                  :prop="'powerAttrList.' + index + '.idCardNo'"
                  :rules="[{ required: true, message: '请输入身份证号',trigger: 'blur'},
                  { required: true, pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: ['blur'] }]"
                >
                  <el-input :disabled="disabledFlag" v-model="item.idCardNo" @change="go(index)" placeholder="请输入身份证号" />
                </el-form-item>
                 <el-form-item
                  label="民族"
                  :prop="'powerAttrList.' + index + '.national'"
                  
                >
                <!--:rules="[{ required: true, message: '请选择民族',trigger: 'change'}]"-->
                <DicSelect :disabledFlag="disabledFlag" dictType = "民族" :dictValue="item.national" v-on:dictValue="item.national=$event"/>
                </el-form-item>
                <el-form-item
                  label="婚姻情况"
                  :prop="'powerAttrList.' + index + '.marriageStatus'"
                  
                >
                <!--:rules="[{ required: true, message: '请选择婚姻情况',trigger: 'change'}]"-->
                <DicSelect dictType = "婚姻情况" :dictValue="item.marriageStatus" v-on:dictValue="item.marriageStatus=$event"/>
                </el-form-item>
               

                 <!-- <el-form-item
                  label="工作单位"
                  :prop="'powerAttrList.' + index + '.workCompany'"
                >
                  <el-input v-model="item.workCompany" placeholder="请输入工作单位" />
                </el-form-item>
                 <el-form-item
                  label="岗位/职务"
                  :prop="'powerAttrList.' + index + '.position'"
                >
                  <el-input v-model="item.position" placeholder="请输入岗位/职务" />
                </el-form-item>
                 <el-form-item
                  label="工作地址"
                  :prop="'powerAttrList.' + index + '.workAddress'"
                >
                  <el-input v-model="item.workAddress" placeholder="请输入工作地址" />
                </el-form-item> -->
                 <el-form-item
                  label="性别"
                  :prop="'powerAttrList.' + index + '.sex'"
                  :rules="[{ required: true, message: '请选择性别',trigger: 'change'}]"
                >
                  <el-radio-group :disabled="disabledFlag" v-model="item.sex">
                      <el-radio label="1">男</el-radio>
                      <el-radio label="2">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  label="年龄"
                  :prop="'powerAttrList.' + index + '.age'"
                  :rules="[{ required: true, message: '请输入年龄',trigger: 'blur'}]"
                >
                  <el-input type="number" v-model="item.age" placeholder="请输入年龄" >
                     <template slot="append">岁</template>
                  </el-input>
                </el-form-item>
                <el-form-item
                  label="联系方式"
                  :prop="'powerAttrList.' + index + '.mobile'"
                  :rules="[{ required: true, message: '请输入联系方式',trigger: 'blur'},
                  { required: false, pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: ['blur'] }]"
                >
                  <el-input v-model="item.mobile" placeholder="请输入联系方式" />
                </el-form-item>
                <el-form-item
                  label="现居住地址"
                  :prop="'powerAttrList.' + index + '.liveAddress'"
                 
                >
                <!--:rules="[{ required: true, message: '请输入现居住地址',trigger: 'blur'}]"-->
                  <el-input v-model="item.liveAddress" placeholder="请输入现居住地址" />
                </el-form-item>
                <el-form-item
                  label="户籍所在地"
                  :prop="'powerAttrList.' + index + '.householdAddress'"
                  
                >
                <!--:rules="[{ required: true, message: '请输入户籍所在地',trigger: 'blur'}]"-->
                  <el-input v-model="item.householdAddress" placeholder="请输入户籍所在地" />
                </el-form-item>
                <el-form-item
                  label="电子邮箱"
                  :prop="'powerAttrList.' + index + '.email'"
                 
                >
                <!--:rules="[{ required: true, message: '请输入电子邮箱',trigger: 'blur'},
                  { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur'] }]"-->
                  <el-input v-model="item.email" placeholder="请输入电子邮箱" />
                </el-form-item>
                <el-form-item
                  label="家庭成员数"
                  :prop="'powerAttrList.' + index + '.famliyNum'"
                  
                >
                <!--:rules="[{ required: true, message: '请输入家庭成员数',trigger: 'blur'}]"-->
                  <el-input type="number" v-model="item.famliyNum" placeholder="请输入家庭成员数" />
                </el-form-item>
                <el-form-item
                  label="银行卡号码"
                  :prop="'powerAttrList.' + index + '.bankCard'"
                  
                >
                <!--:rules="[{ required: true, message: '请输入银行卡号码',trigger: 'blur'},
                  { required: true, min:16,max:19, message: '请输入正确的银行卡号码', trigger: ['blur'] }]"-->
                  <el-input v-model="item.bankCard" placeholder="请输入银行卡号码" />
                </el-form-item>
                <el-form-item style="float:right;">
                  <el-button
                  type="danger"
                  size="medium"
                  @click="removeRow(index)"
                >删除</el-button>
                </el-form-item>
        </el-collapse-item>
        
      </el-collapse>
         <el-form-item style="margin-top:90px;">
        <div v-if=" defaultChangeValue === 'detail'">
          <el-button  type="primary" @click="addRow" style="width:150px;height:40px;">新增共款人</el-button>
          <el-button  type="warning" @click="createData" style="width:150px;height:40px;">保存</el-button>
        </div>
        <div v-else>
           <el-button  type="primary" @click="addRow" style="width:150px;height:40px;">新增共款人</el-button>
           <el-button  type="primary" @click="batchSaveOwnerBorrowerDraft(1)" style="width:150px;height:40px;">上一步</el-button>
           <el-button  type="warning" @click="createData(2)" style="width:150px;height:40px;">下一步</el-button>
        </div>
      </el-form-item>
      </el-form>

    
      </el-card>

  </div>
</template>

<style scoped>
.parentColl >>> .el-collapse-item__header{
  min-height: 95px;
  font-size: 20px;
  font-weight: 1000;
  padding:20px;
}

</style>

<script>
import { getAgeAndSex } from '@/utils/validate';
import { batchSaveOwnerBorrower,batchSaveOwnerBorrowerDraft,batchUpdateOwnerBorrower,
findListByProjectId,listPayeeByClientId,deleteOwner } from '@/api/borrower'
import DicSelect from '@/components/select'
export default {
  name: 'borrower',
  components: { DicSelect },
  // 接受父组件的值
  props: {
     changeValue: undefined,
     projectId: undefined,
     operation: undefined
    },  
  data() {
    return {
      activeNames:"",
      num:1,
      active: 0,
      updateParam: undefined,
      list: undefined,
      total: 0,
      listLoading: true,
      options:[],
      value:undefined,
      borrowerId: undefined,
      stepType: undefined,
      disabledFlag: false,
      defaultChangeValue: this.changeValue,
      data: [{
      }],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      rules: {
        name: [
          { required: true, message: '姓名', trigger: 'blur' }
        ]
      },
      downloadLoading: false,
      formData3: {
        powerAttrList: []
      },
    }
  },
  watch: {
    "changeValue":function(val){
      this.defaultChangeValue = val
    }
  },
  computed: {
  },
  created() {
     var form = localStorage.getItem("borrowerList")
    if(form!= undefined){
      this.formData3.powerAttrList = JSON.parse(form)
    } 
    //编辑进件
    if(this.projectId!=undefined) {
      this.findListByProjectId()
      this.defaultChangeValue = "detail"
    }
    //进件回填
    this.borrowerId = localStorage.getItem("borrowerId")
    console.log(this.borrowerId)
    if( this.borrowerId != undefined ) {
      this.listPayeeByClientId()
    }
  },
  methods: {
     addRow() {
      this.formData3.powerAttrList.push({
        realName: undefined,
        idCardNo: undefined,
        national: undefined,
        marriageStatus: undefined,
        sex: undefined,
        age: undefined,
        mobile: undefined,
        liveAddress: undefined,
        householdAddress: undefined,
        email: undefined,
        famliyNum: undefined,
        bankCard: undefined,
        title:"共款人信息栏"+(this.formData3.powerAttrList.length+1),
        num: (this.formData3.powerAttrList.length+1)+"",
        // key: new Date(),
        borrowerId:this.borrowerId
      });
       this.formData3.powerAttrList.forEach((item,index)=>{
                item.title = "共款人信息栏"+(index+1)
                item.num = (index+1)+""
            })
      this.activeNames = this.formData3.powerAttrList.length+""
    },
     // 删除属性列
    removeRow(index) {
      let ownerForm = this.formData3.powerAttrList[index]
      console.log(ownerForm)
      deleteOwner({borrowerId:ownerForm.id})
        .then(response => {
            this.$notify.success("删除成功")
            this.formData3.powerAttrList.splice(index, 1);
            this.formData3.powerAttrList.forEach((item,index)=>{
                item.title = "共款人信息栏"+(index+1)
            })
        })
        .catch(() => {
          this.$notify.error("删除失败")
        })
      
    },
    findListByProjectId() {
      this.listLoading = true
      findListByProjectId({projectId:this.projectId})
        .then(response => {
          if(response.data != undefined ) {
            // if(response.data.length>0){
            //   this.disabledFlag = true
            // }
            var data = response.data
            for( let i = 0; i< data.length;i++){
              data[i].title = "共款人信息栏"+(i+1)
              data[i].sex = ""+data[i].sex+""
              if( this.borrowerId!=undefined && this.borrowerId!='undefined'){
                data[i].borrowerId = this.borrowerId
              }
            }
          this.num = data.length
          this.formData3.powerAttrList = data
          
          }
        })
        .catch(() => {
          this.resetForm()
        })
    },
    listPayeeByClientId() {
      this.listLoading = true
      listPayeeByClientId({borrowerId:this.borrowerId})
        .then(response => {
          if(response.data != undefined ) {
            // if(response.data.length>0){
            //   this.disabledFlag = true
            // }
            var data = response.data
            for( let i = 0; i< data.length;i++){
              data[i].title = "共款人信息栏"+(i+1)
              data[i].sex = ""+data[i].sex+""
              data[i].borrowerId = this.borrowerId
            }
            this.num = data.length
          this.formData3.powerAttrList = data
          
          }
        })
        .catch(() => {
          this.resetForm()
        })
    },
          // 实现自动生成生日，性别，年龄
      go(index) {
        console.log(index)
        let item = this.formData3.powerAttrList[index]
        let val = item.idCardNo
        let borrower = getAgeAndSex(val)
        console.log(borrower)
        console.log(item)
        item.sex = borrower.sex;//性别
        item.age = borrower.age;//年龄
        
      },
    createData(val) {
      this.stepType = val
      // if(this.stepType === 1 ) {
      //   localStorage.setItem("backBorrowerId",this.borrowerId)
      // }
      if( this.formData3.powerAttrList.length > 0 ) {
        // localStorage.setItem("borrowerList",JSON.stringify(this.formData3.powerAttrList))
      this.$refs['formData3'].validate(valid => {
        if (valid) {
          console.log(this.formData3)
          if( this.operation === 'add' || this.formData3.powerAttrList[0].id == undefined) {
            this.batchSaveOwnerBorrower()
          }else{
            this.batchUpdateOwnerBorrower()
          }
        }
      })
      }else{
            if(this.defaultChangeValue != 'detail' ) {
              this.$emit("stepChanged",this.stepType === 1 ? 1 : 3)
            }
      }
    },
    batchSaveOwnerBorrowerDraft(val){
        this.stepType = val
        if( this.formData3.powerAttrList.length > 0 ) {
        let paramFlag = true
        let ownerList = this.formData3.powerAttrList
        for( let i=0 ; i< ownerList.length; i++) {
          if(ownerList[i].idCardNo === undefined || 
              ownerList[i].sex === undefined){
             paramFlag = false
             break;
          }
        }
        if( !paramFlag) {
          this.$message.error("保存草稿也必须填写身份证号，民族，性别哦，方便下次进件回填信息")
          return false
        }
        batchSaveOwnerBorrowerDraft(this.formData3.powerAttrList)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '草稿保存成功'
              })
              if( this.stepType == 2) {
                this.$router.push("/project/index")
              }else{
                 localStorage.setItem("projectIdByDraw",1)
                if(this.defaultChangeValue != 'detail' && val == 1 ) {
                  localStorage.setItem("isBack",true)//标识是从共款人上一步过去借款人页面的  不删除身份证
                  this.$emit("stepChanged",this.stepType === 1 ? 1 : 3)
                }
              }
              
            })
            .catch(response => {
            })
        }else if(this.stepType == 1){
            if(this.defaultChangeValue != 'detail' && val == 1 ) {
                  localStorage.setItem("projectIdByDraw",1)
                  localStorage.setItem("isBack",true)//标识是从共款人上一步过去借款人页面的  不删除身份证
                  this.$emit("stepChanged",this.stepType === 1 ? 1 : 3)
          }
        }
         
    },
    batchSaveOwnerBorrower(){
        batchSaveOwnerBorrower(this.formData3.powerAttrList)
            .then(response => {
               if(this.defaultChangeValue != 'detail' ) {
                    this.$emit("stepChanged",this.stepType === 1 ? 1 : 3)
                }
              this.$notify.success({
                title: '成功',
                message: '保存成功'
              })
            })
            .catch(response => {
            })
    },
    batchUpdateOwnerBorrower(){
        let projectIdByDraw = localStorage.getItem("projectIdByDraw")
        if( projectIdByDraw == undefined ) {
          projectIdByDraw = this.projectId
        }
        this.formData3.powerAttrList.forEach(item =>{
          item.projectId = projectIdByDraw
        })
        batchUpdateOwnerBorrower(this.formData3.powerAttrList)
            .then(response => {
               if(this.defaultChangeValue != 'detail' ) {
                    this.$emit("stepChanged",this.stepType === 1 ? 1 : 3)
                }
              this.$notify.success({
                title: '成功',
                message: '修改成功'
              })
            })
            .catch(response => {
            })
    },
  }
}
</script>
